package nz.ac.massey.cs.se400_2013.ass3.gui;

import java.awt.FlowLayout;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;

import nz.ac.massey.cs.se400_2013.ass3.Address;
import nz.ac.massey.cs.se400_2013.ass3.Course;
import nz.ac.massey.cs.se400_2013.ass3.Paper;
import nz.ac.massey.cs.se400_2013.ass3.Student;
import nz.ac.massey.cs.se400_2013.ass3.plugin.AddressEditor;
import nz.ac.massey.cs.se400_2013.ass3.plugin.ChangeListener;
import nz.ac.massey.cs.se400_2013.ass3.plugin.CourseEditor;
import nz.ac.massey.cs.se400_2013.ass3.plugin.PaperEditor;
import nz.ac.massey.cs.se400_2013.ass3.plugin.StudentEditor;

public class DomainEditor extends JFrame {

	private Toolbar tool = new Toolbar();
	private SideTree sideTree = new SideTree(this.tool);
	private JPanel currentEditor = new JPanel(); //= (new DefaultEditor().edit(new Student())).getEditor(); //just to fill space since we dont know which plugin to use
	
	public DomainEditor() {
		super();
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setJMenuBar(tool);
		
		this.sideTree.addTreeSelectionHandler(new SelectionHandler());
		setLayout(new GridLayout(1, 2));
		this.currentEditor.setLayout(new FlowLayout());
		tool.addPaperHandler(new AddPaperHandler(sideTree));
		tool.addCourseHandler(new AddCourseHandler(sideTree));
		tool.addStudentHandler(new AddStudentHandler(sideTree));
		tool.addDeleteHandler(new DeleteHandler(sideTree));
		tool.addSaveHandler(new SaveHandler(sideTree));

		
		add(sideTree);
		add(currentEditor);
		setSize(1000, 500);
		setVisible(true);
	}

	public static void main(String[] args) {
		new DomainEditor();
	}


	private class SelectionHandler implements TreeSelectionListener{

		public void valueChanged(TreeSelectionEvent e) {
			tool.setSaveEnabled(false);
			Object currentObject = sideTree.getCurrentObject();
			AddressEditor editor = new AddressEditor();
			editor.edit(new Address());
			editor.addChangeListener(new ChangeHandler());
			currentEditor.removeAll();
			JPanel neweditor = editor.getEditor();
			currentEditor.add(neweditor);
			currentEditor.repaint();
			currentEditor.revalidate();
		}
		
	}
	
	private class ChangeHandler implements ChangeListener{

		@Override
		public void change() {
			tool.setSaveEnabled(true);
		}
		
	}
}
